<template>
  <div class="flex-1 flex flex-col bg-white">
    <!-- 角色信息头部 -->
    <div class="h-16 border-b border-gray-200 flex items-center justify-between px-6 bg-white">
      <div v-if="character" class="flex items-center">
        <el-avatar :src="character.avatarUrl" :size="40">
          <el-icon><Avatar /></el-icon>
        </el-avatar>
        <div class="ml-3">
          <h2 class="font-semibold text-gray-800">{{ character.name }}</h2>
          <div class="text-sm text-green-500 flex items-center">
            <div class="w-2 h-2 bg-green-400 rounded-full mr-2"></div>
            在线
          </div>
        </div>
      </div>
      
      <div class="flex items-center space-x-2">
        <el-button circle @click="openCharacterSettings">
          <el-icon><Setting /></el-icon>
        </el-button>
        <el-button circle @click="openMoreActions">
          <el-icon><MoreFilled /></el-icon>
        </el-button>
      </div>
    </div>
    
    <!-- 聊天记录区域 -->
    <div ref="chatContainer" class="flex-1 overflow-y-auto p-6 space-y-4 bg-gray-50" style="max-height: calc(100vh - 200px);">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="text-center py-12">
        <el-avatar :src="character?.avatarUrl" :size="80" class="mb-4">
          <el-icon size="40"><Avatar /></el-icon>
        </el-avatar>
        <h3 class="text-lg font-semibold text-gray-800 mb-2">开始与{{ character?.name }}对话</h3>
        <p class="text-gray-500">{{ character?.description }}</p>
      </div>
      
      <!-- 消息列表 -->
      <div
        v-for="message in messages"
        :key="message.id"
        class="message-wrapper"
        :class="message.senderType === 1 ? 'user-message' : 'ai-message'"
      >
        <!-- 用户消息 -->
        <div v-if="message.senderType === 1" class="flex justify-end">
          <div class="max-w-md">
            <div class="bg-blue-500 text-white rounded-2xl rounded-br-md px-4 py-3 shadow-sm">
              <p class="text-sm">{{ message.content }}</p>
              
              <!-- 语音播放控件（如果是语音消息） -->
              <div v-if="message.contentType === 'voice' && message.voiceUrl" class="flex items-center mt-3 pt-2 border-t border-blue-400">
                <el-button
                  :icon="isPlaying(message.id) ? 'VideoPause' : 'VideoPlay'"
                  size="small"
                  circle
                  @click="toggleVoicePlay(message)"
                />
                <div class="flex-1 mx-3">
                  <div class="h-1 bg-blue-300 rounded-full overflow-hidden">
                    <div 
                      class="h-full bg-white transition-all duration-300"
                      :style="{ width: getPlayProgress(message.id) + '%' }"
                    ></div>
                  </div>
                </div>
                <span class="text-xs text-blue-100">{{ formatDuration(message.id) }}</span>
              </div>
            </div>
            <div class="text-xs text-gray-400 mt-1 text-right">
              {{ formatMessageTime(message.createdAt) }}
            </div>
          </div>
        </div>
        
        <!-- AI消息 -->
        <div v-else class="flex items-start space-x-3">
          <el-avatar :src="character?.avatarUrl" :size="32">
            <el-icon><Avatar /></el-icon>
          </el-avatar>
          <div class="max-w-md">
            <div class="bg-white rounded-2xl rounded-bl-md px-4 py-3 shadow-sm border border-gray-100">
              <p class="text-sm text-gray-800">{{ message.content }}</p>
              
              <!-- 语音播放控件 -->
              <div v-if="message.voiceUrl" class="flex items-center mt-3 pt-2 border-t border-gray-100">
                <el-button
                  circle
                  size="small"
                  @click="toggleVoicePlay(message)"
                >
                  <el-icon>
                    <component :is="isPlaying(message.id) ? 'VideoPause' : 'VideoPlay'" />
                  </el-icon>
                </el-button>
                <div class="flex-1 mx-3">
                  <div class="h-1 bg-gray-200 rounded-full overflow-hidden">
                    <div 
                      class="h-full bg-blue-500 transition-all duration-300"
                      :style="{ width: getPlayProgress(message.id) + '%' }"
                    ></div>
                  </div>
                </div>
                <span class="text-xs text-gray-500">{{ formatDuration(message.id) }}</span>
              </div>
            </div>
            <div class="text-xs text-gray-400 mt-1 flex items-center justify-between">
              <span>{{ formatMessageTime(message.createdAt) }}</span>
              <span v-if="message.emotionType" class="emotion-tag">
                {{ getEmotionLabel(message.emotionType) }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- AI正在输入指示器 -->
      <div v-if="isLoading" class="flex items-center space-x-3">
        <el-avatar :src="character?.avatarUrl" :size="32">
          <el-icon><Avatar /></el-icon>
        </el-avatar>
        <div class="bg-white rounded-2xl rounded-bl-md px-4 py-3 shadow-sm border border-gray-100">
          <div class="typing-indicator">
            <span></span><span></span><span></span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 语音控制面板 -->
    <VoiceControlPanel
      @send-text="handleSendText"
      @send-voice="handleSendVoice"
      @toggle-progress-panel="handleToggleProgressPanel"
      :is-recording="isRecording"
      :is-processing="isProcessing"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Avatar, 
  Setting, 
  MoreFilled, 
  VideoPlay, 
  VideoPause 
} from '@element-plus/icons-vue'
import VoiceControlPanel from './VoiceControlPanel.vue'
import { formatMessageTime } from '@/utils/time'
import { formatDuration } from '@/utils/audio'
import type { Character, Message } from '@/types/chat'
import { useChatStore } from '@/stores/chat'

// Props
interface Props {
  character: Character | undefined
  messages: Message[]
  isLoading: boolean
  isRecording: boolean
  isProcessing: boolean
}
const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'send-message': [content: string]
  'send-voice': [audioBlob: Blob]
  'toggle-progress-panel': [show: boolean]
}>()

// Store
const chatStore = useChatStore()

// 响应式数据
const chatContainer = ref<HTMLElement>()
const playingAudios = ref<Set<number>>(new Set())
const audioElements = ref<Map<number, HTMLAudioElement>>(new Map())
const audioProgress = ref<Map<number, number>>(new Map())
const audioDuration = ref<Map<number, number>>(new Map())

// 监听消息变化，自动滚动到底部
watch(() => props.messages.length, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 监听AI语音自动播放
watch(() => chatStore.autoPlayAIVoice, (autoPlayData) => {
  if (autoPlayData) {
    console.log('🎵 自动播放AI语音:', autoPlayData)
    // 找到对应的消息并播放
    const message = props.messages.find(m => m.id === autoPlayData.messageId)
    if (message && message.voiceUrl) {
      // 延迟一点时间确保DOM已更新
      nextTick(() => {
        toggleVoicePlay(message)
      })
    }
    // 清除自动播放状态
    chatStore.autoPlayAIVoice = null
  }
})

// 方法
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

const handleSendText = (content: string) => {
  emit('send-message', content)
}

const handleSendVoice = (audioBlob: Blob) => {
  emit('send-voice', audioBlob)
}

const toggleVoicePlay = (message: Message) => {
  if (!message.voiceUrl) return
  
  const messageId = message.id
  const isCurrentlyPlaying = playingAudios.value.has(messageId)
  
  if (isCurrentlyPlaying) {
    // 停止播放
    const audio = audioElements.value.get(messageId)
    if (audio) {
      audio.pause()
      playingAudios.value.delete(messageId)
    }
  } else {
    // 开始播放
    let audio = audioElements.value.get(messageId)
    if (!audio) {
      audio = new Audio(message.voiceUrl)
      audioElements.value.set(messageId, audio)
      
      // 加载完成后获取时长
      audio.onloadedmetadata = () => {
        if (audio.duration) {
          audioDuration.value.set(messageId, audio.duration)
          console.log(`语音时长: ${audio.duration}秒`)
        }
      }
      
      audio.onended = () => {
        playingAudios.value.delete(messageId)
      }
      
      audio.onerror = () => {
        console.error('语音播放错误:', audio.error)
        ElMessage.error('语音播放失败')
        playingAudios.value.delete(messageId)
      }
      
      // 添加时间更新事件，用于进度条显示
      audio.ontimeupdate = () => {
        if (playingAudios.value.has(messageId) && audio.duration) {
          const progress = (audio.currentTime / audio.duration) * 100
          audioProgress.value.set(messageId, progress)
        }
      }
    }
    
    audio.play().catch(error => {
      console.error('播放语音失败:', error)
      ElMessage.error('语音播放失败')
    })
    playingAudios.value.add(messageId)
  }
}

const isPlaying = (messageId: number) => {
  return playingAudios.value.has(messageId)
}

const getPlayProgress = (messageId: number) => {
  return audioProgress.value.get(messageId) || 0
}

const formatDuration = (messageId: number) => {
  const duration = audioDuration.value.get(messageId)
  if (!duration) return '0:00'
  const minutes = Math.floor(duration / 60)
  const seconds = Math.floor(duration % 60)
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
}

// 切换进度面板显示
const handleToggleProgressPanel = (show: boolean) => {
  emit('toggle-progress-panel', show)
}

const getEmotionLabel = (emotion: string) => {
  const labels: Record<string, string> = {
    'happy': '😊',
    'sad': '😢', 
    'angry': '😠',
    'neutral': '😐',
    'excited': '🤩',
    'worried': '😟',
    'calm': '😌'
  }
  return labels[emotion] || emotion
}

const openCharacterSettings = () => {
  ElMessage.info('角色设置功能开发中...')
}

const openMoreActions = () => {
  ElMessage.info('更多操作功能开发中...')
}
</script>

<style scoped>
.message-wrapper {
  @apply mb-4;
}

.typing-indicator {
  @apply flex space-x-1;
}

.typing-indicator span {
  @apply w-2 h-2 bg-gray-400 rounded-full;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% { 
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% { 
    transform: scale(1);
    opacity: 1;
  }
}

.emotion-tag {
  @apply text-xs bg-gray-100 px-2 py-1 rounded-full;
}

/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 4px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 2px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .max-w-md {
    @apply max-w-xs;
  }
  
  .px-6 {
    @apply px-4;
  }
  
  .space-x-3 > * + * {
    @apply ml-2;
  }
}
</style>

